package main

import (
	"fmt"
	"io"
	"net/http"

	"github.com/vmware-labs/wasm-workers-server/kits/go/worker"
)

func main() {
	worker.ServeFunc(func(w http.ResponseWriter, r *http.Request) {
		var payload string

		reqBody, err := io.ReadAll(r.Body)
		if err != nil {
			panic(err)
		}
		r.Body.Close()

		if len(reqBody) == 0 {
			payload = "-"
		} else {
			payload = string(reqBody)
		}

		body := fmt.Sprintf("<!DOCTYPE html>"+
			"<head>"+
			"<title>Wasm Workers Server</title>"+
			"<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">"+
			"<meta charset=\"UTF-8\">"+
			"<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/water.css@2/out/water.css\">"+
			"<style>"+
			"body { max-width: 1000px; }"+
			"main { margin: 5rem 0; }"+
			"h1, p { text-align: center; }"+
			"h1 { margin-bottom: 2rem; }"+
			"pre { font-size: .9rem; }"+
			"pre > code { padding: 2rem; }"+
			"p { margin-top: 2rem; }"+
			"</style>"+
			"</head>"+
			"<body>"+
			"<main>"+
			"<h1>Hello from Wasm Workers Server 👋</h1>"+
			"<pre><code>Replying to %s<br>"+
			"Method: %s<br>"+
			"User Agent: %s<br>"+
			"Payload: %s</code></pre>"+
			"<p>"+
			"This page was generated by a Go file running in WebAssembly."+
			"</p>"+
			"</main>"+
			"</body>", r.URL.String(), r.Method, r.UserAgent(), payload)

		w.Header().Set("x-generated-by", "wasm-workers-server")
		w.Write([]byte(body))
	})
}
